import {Component} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from "@angular/router";
import {phoneCustomizedValidator} from "./phone-validator.function";
import {User} from "../../../shared/model/user.interface";
import {UserApiService} from "../../../core/api/user-api.service";

@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.css']
})
export class EditUserComponent {

  userForm?: FormGroup;

  genderOpts = [{label: 'Male', value: 1}, {label: 'Female', value: 2}, {label: 'Other', value: 3}];

  constructor(private readonly _fb: FormBuilder,
              private readonly _userApiClient: UserApiService,
              private readonly _router: Router,
              private readonly _activatedRoute: ActivatedRoute) {
    this._activatedRoute.params.subscribe(({id}) => {
      if (id !== 'new') {
        this._userApiClient.getUserById(+id).subscribe((user: User) => {
          this.userForm = this._fb.group(
            {
              id: [user.id],
              username: [user.username, Validators.required],
              name: [user.name, Validators.required],
              gender: [user.gender, Validators.required],
              isAdmin: [user.isAdmin, Validators.required],
              birthday: [new Date(user.birthday), Validators.required],
              phoneNum: [user.phoneNum, [
                Validators.required,
                phoneCustomizedValidator()
              ]],
              homeAddress: [user.homeAddress, Validators.required]
            }
          );
        });
      } else {
        this.userForm = this._fb.group(
          {
            id: [null],
            username: [null, Validators.required],
            password: [null, [Validators.required, Validators.minLength(6)]],
            name: [null, Validators.required],
            gender: [1, Validators.required],
            isAdmin: [false, Validators.required],
            birthday: [null, Validators.required],
            phoneNum: [null, [
              Validators.required,
              phoneCustomizedValidator()
            ]],
            homeAddress: [null, Validators.required],
            acceptTerms: [false, Validators.requiredTrue]
          }
        );
      }
    });
  }

  onSubmit() {
    const request = this.control('id')?.value ?
      this._userApiClient.update(+this.control('id')!.value, this.userForm!.value) :
      this._userApiClient.create(this.userForm!.value);
    request.subscribe(() => {
      this._router.navigateByUrl('/admin/users');
    });
  }

  control(controlName: string): AbstractControl | undefined | null {
    return this.userForm?.get(controlName);
  }
}
